<?php

namespace app\tool\controller;

// use app\admin\model\Upload;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Config;

class UploadController {

	static public function upload($file, $folder, $imageUrl, $fileName = "") {
		$accessKey = Config::get('app.qi_niu.accessKey');
		$bucket = Config::get('app.qi_niu.bucket');
		$secretKey = Config::get('app.qi_niu.secretKey');
		$folder = Config::get('app.qi_niu.folder');
		$url = Config::get('app.qi_niu.url');
		if ($imageUrl) {
			$ext = pathinfo($imageUrl, PATHINFO_EXTENSION);
			$data_name = date('Ymd');
			$img_name = date('YmdHis') . rand(000000, 999999) . '.' . $ext;
			$imgkey = $data_name . '/' . $img_name;
			$newImageName = $folder . '/uploads/' . $imgkey;
			$auth = new Auth($accessKey, $secretKey);
			$token = $auth->uploadToken($bucket);
			$uploadMgr = new UploadManager();

			$filePath = self::getImgData($imageUrl);

			if (!$filePath) {
				return ['code' => 200, 'img' => '失败'];
			}

			list($ret, $err) = $uploadMgr->put($token, $newImageName, $filePath, null, 'image/jpeg');
			if (!$err) {
				return $url . $ret['key'];
//                return ['code' => 200, 'img' => $url . $ret['key']];
			} else {
				return $err;
			}

		} else {
			try {
				$inserData = [];
				$filePath = $file->getRealPath();
				$ext = pathinfo($_FILES[$fileName]['name'], PATHINFO_EXTENSION);
				$inserData['from_name'] = $_FILES[$fileName]['name'];
				$data_name = date('Ymd');
				$img_name = date('YmdHis') . rand(000000, 999999) . '.' . $ext;
				$imgkey = $data_name . '/' . $img_name;
				$newImageName = $folder . '/uploads/' . $imgkey;
				$auth = new Auth($accessKey, $secretKey);
				$token = $auth->uploadToken($bucket);
				$uploadMgr = new UploadManager();
				list($ret, $err) = $uploadMgr->putFile($token, $newImageName, $filePath);
				$inserData['qn_url'] = $url . $ret['key'];
				$inserData['create_time'] = date('Y-m-d H:i:s');
				if (!$err) {
					// upload::insert($inserData);
					return $url . $ret['key'];
//                    return ['code' => 200, 'img' => $url . $ret['key']];
				} else {
					return $err;
				}
			} catch (UploadException $e) {
				return $e->getMessage();
			}
		}
	}
	static public function getImgData($img_url) {
		$ch = curl_init($img_url);

		// 基本配置
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

		// 允许重定向（最多5次）
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 5);

		// 设置User-Agent模拟浏览器
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36');

		// 超时设置
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);

		// 忽略SSL证书验证（测试用，生产环境应配置证书）
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

		// 执行请求
		$rawData = curl_exec($ch);

		// 检查cURL错误
		if ($rawData === false) {
			$error = curl_error($ch);
			curl_close($ch);
			throw new Exception("cURL Error: " . $error);
		}

		// 检查HTTP状态码
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if ($httpCode !== 200) {
			curl_close($ch);
			throw new Exception("HTTP Error: Status Code " . $httpCode);
		}

		curl_close($ch);
		return $rawData;
	}

	/*static public function getImgData($img_url) {

		$ch = curl_init($img_url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

		$rawData = curl_exec($ch);
		curl_close($ch);

		return $rawData;
	}*/
}
